﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace XRpgLibrary.ExtensionMethods
{
    public static class VectorExtension
    {
        public static Rectangle ToRectangle(this Vector4 v)
        {
            return new Rectangle((int)v.X, (int)v.Y, (int)v.W, (int)v.Z);
        }

        public static Vector2 IntersectionRepelVector(this Vector4 thisRect, Vector4 otherRect)
        {
            if (thisRect.Intersects(otherRect))
            {
                int signX = thisRect.GetRight() > otherRect.GetRight() ? -1 : 1;
                int signY = thisRect.GetTop() > otherRect.GetTop() ? -1 : 1;

                float x = Math.Min(thisRect.GetRight(), otherRect.GetRight()) - Math.Max(thisRect.GetLeft(), otherRect.GetLeft());
                float y = Math.Min(thisRect.GetBottom(), otherRect.GetBottom()) - Math.Max(thisRect.GetTop(), otherRect.GetTop());

                if (Math.Abs(x) < Math.Abs(y))
                    return new Vector2(x * signX, 0);
                
                if (Math.Abs(y) < Math.Abs(x))
                    return new Vector2(0, y * signY);

                return new Vector2(x * signX, y * signY);
            }

            return Vector2.Zero;
        }

        public static bool Intersects(this Vector4 a, Vector4 b)
        {
            if (a.X > b.X + b.W)
                return false;

            if (a.X + a.W < b.X)
                return false;

            if (a.Y + a.Z < b.Y)
                return false;

            if (a.Y > b.Y + b.Z)
                return false;

            return true;
        }

        public static float GetRight(this Vector4 v)
        {
            return v.X + v.W;
        }

        public static float GetLeft(this Vector4 v)
        {
            return v.X;
        }

        public static float GetTop(this Vector4 v)
        {
            return v.Y;
        }

        public static float GetBottom(this Vector4 v)
        {
            return v.Y + v.Z;
        }
    }
}
